package com.scalar.chiptrack.operations.dataentry.inventoryTransit.actioncommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.operations.dataentry.inventoryTransit.forms.InventoryTransitForm;
import com.scalar.chiptrack.operations.dataentry.LotDetails;
import com.scalar.chiptrack.operations.dataentry.dao.DataEntryDAO;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.sales.SubTotal;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Iterator;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 3 Jun, 2010
 * Time: 10:34:54 AM
 * To change this template use File | Settings | File Templates.
 */
public class ProgramOutTransactionSaveCommand extends ActionCommand
{
    private static final String ACTION_NAME = "/inventoryOutTrans.do";

    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception
    {

        InventoryTransitForm inventoryTransitForm = (InventoryTransitForm) form;

        HashMap<String,String> errors   = new HashMap<String,String>();
        HashMap<String,String> info     = new HashMap<String,String>();
        String action = request.getParameter("action");
        System.out.println("action = " + action);
        request.setAttribute(INFO_MESSAGES, info);
        request.setAttribute(ERROR_MESSAGES, errors);

        HttpSession mSession = request.getSession();
        User user = (User) mSession.getAttribute(SessionKeys.USER_KEY);

        if (user == null)
        {
            mSession.setAttribute(SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
            return (mapping.findForward("login"));
        }
        else
        {
            if (user.isActionAllowed(Functionality.DATA_ENTRY, User.USER_ACTION_MODIFY) )
            {
                request.setAttribute("showMessage", "FALSE");
            }
            else
            {
                request.setAttribute("showMessage", "TRUE");
            }
        }

        LotDetails invTransitLots = null;

        if ( "programOutsave".equalsIgnoreCase( action ) )
        {
            LinkedHashMap hash = new LinkedHashMap();
            ArrayList arrList  = new ArrayList();

           //for Confirm Screen
            for (int i = 0; i < inventoryTransitForm.getWipLotsList().size(); i++)
            {
                invTransitLots = (LotDetails) inventoryTransitForm.getWipLotsList().get(i);

                if ( invTransitLots.isChecked() )
                {
                    String partNo = ProductDao.getProductNameByProcessStep_Id( invTransitLots.getToProcessStepId() );
                    invTransitLots.setToPartNumber( partNo );
                    String partNumber = invTransitLots.getPartNumber();
                    if ( !( hash.containsKey ( partNumber ) ) )
                    {
                        hash.put ( partNumber, new ArrayList() );
                    }
                    arrList = (ArrayList) hash.get ( partNumber );

                    arrList.add ( invTransitLots );
                }
            }

            Iterator iterator = hash.keySet().iterator();
            LinkedHashMap hashMap = new LinkedHashMap ();

            while ( iterator.hasNext () )
            {
                String str = ( String ) iterator.next ();
                ArrayList newarrList = ( ArrayList )hash.get ( str );
                SubTotal subTotal = new SubTotal();
                int subTotalQty = 0;
                int scrapsubTotalQty = 0;

                for ( int j = 0; j < newarrList.size (); j++ )
                {
                    subTotalQty = subTotalQty + Integer.parseInt(( (LotDetails)newarrList.get( j ) ).getShipDieQty() );
                    scrapsubTotalQty = scrapsubTotalQty + ( (LotDetails)newarrList.get( j ) ).getScrapDieQty();
                }
                subTotal.setSubTotalQty( Integer.toString ( subTotalQty )  );
                subTotal.setSubTotalProposedQty( Integer.toString ( scrapsubTotalQty )  );

                hashMap.put ( newarrList, subTotal );
            }

            request.setAttribute("subTotalMap", hashMap );

            request.setAttribute("action", action);

            saveToken( request );
            return mapping.findForward( "programOutTransConfirm" );
        }
        else
        {
            if ( isTokenValid( request ))
            {
                try
                {
                    DataEntryDAO.saveInventoryProgramLotsInfo( null, inventoryTransitForm, user.getUserName() );

                    resetToken( request );
                    info.put ( "FG Inventory Transit Lot Information Saved", null );
                }
                catch( Exception e )
                {
                    e.printStackTrace();
                    errors.put( "Error storing the FG Inventory Transit Lot information", null );
                }
            }
            else
            {
                 errors.put("Invalid Request" , null );
            }

            inventoryTransitForm.setProcessStepId(0);
            inventoryTransitForm.setLocationId(0);
            inventoryTransitForm.setWipLotsList( null );

            request.setAttribute("partNumbersList", ProductDao.loadAllPartsForProcessTypeByPsType( LOCATION_TYPE_FG ) );
            request.setAttribute("locationList",    VendorDAO.getInventoryLocationsByProcessByUserType( null, LOCATION_TYPE_FINISHED_GOODS , 0 ) );
            request.setAttribute("action", action);
        }
        return mapping.findForward("programOutTrans");
    }
}
